$(document).ready(function () {

    /*
     1 - 管理员 （研工部）
     2 - 普通用户
     3 - 特殊用户 （院办 教务）
     */


    $('#btn-manage-account').attr('class', 'navbar-btn btn btn-default btn-active');
    $('title').html("用户账号管理");
    //查看用户信息
    $('.show-account').click(function () {
        var id = $(this).attr('role');
        //查看用户信息  update: 1-查看 2-修改（更新）
        $(location).attr('href', '/account-show?id=' + id + '&update=' + 1);
    });

    // automatically toggle focus between the email modal window and the login form //
    $('#get-user-msg').on('shown.bs.modal', function () {
        $('#msg-tf').focus();
    });

    retrievePasswordAlert = $('#get-user-msg .alert');

    //给用户发送邮件通知
    $('#modify-submit').click(function () {
        var msg = $('#msg-tf').val();
        console.log('--- modify submit ---', msg);
        console.log('--- data ---', data);
        // $('#get-msg-form').submit();
        var pathname = window.location.pathname;
        // $('#get-user-msg').modal('hide');

        $.post('/account-update-status', data, function (result) {
            console.log(" account-update-status  ---- return result: ", result);
            if (result.id === 1) {
                //给用户发送通知
                if (msg.trim() !== '') {
                    //提示正在发送邮件
                    retrievePasswordAlert.attr('class', 'alert alert-danger');
                    retrievePasswordAlert.html('正在发送...');
                    retrievePasswordAlert.show();

                    $.post('/user-msg', {
                        'user_id': data['user_id'],
                        'msg': msg,
                        'status': data['status']
                    }, function (result2) {
                        console.log("user-msg  ---- return result: ", result2);
                        if (result2.id == 1) {
                            generateNotify('', '邮件发送成功', 'success', 3000);
                            // retrievePasswordAlert.html('');
                            $('#get-user-msg').modal('hide');
                            setTimeout("$(location).attr('href', window.location.pathname)", 500);
                        } else {
                            //发送邮件失败
                            retrievePasswordAlert.html('');
                            // retrievePasswordAlert.html('邮件发送失败');
                            $('#get-user-msg').modal('hide');
                            generateNotify('', '邮件发送失败, 用户邮箱错误', 'danger', 3000);
                        }
                    });
                } else {
                    retrievePasswordAlert.html('');
                    $('#get-user-msg').modal('hide');
                    generateNotify('', result.msg, 'success', 3000);
                    setTimeout("$(location).attr('href', window.location.pathname)", 500);
                }
            } else {
                //更新用户状态失败
                generateNotify('', result.msg, 'danger', 3000);
                // $(location).attr('href', window.location.pathname);
            }
        });
    });

    var data;
    //同意用户申请
    $('.accpet-account').click(function () {
        var dataStatus = $(this).attr('status');
        if (dataStatus === 'success') {
            generateNotify('', '该账号已申请成功', 'danger');
        } else {
            //设置同意提示信息
            setSuggestions(2);

            var userId = $(this).attr('role');
            var status = 2; //同意
            data = {'user_id': userId, 'status': status};
            $('#msg_title').html('同意用户申请');
            $('#cancel').html('取消');
            $('#modify-submit').html('确认同意');
            $('#modify-submit').show();
            $('#get-user-msg').modal('show');
        }
    });


    //拒绝用户申请
    $('.refuse-account').click(function () {
        var dataStatus = $(this).attr('status');
        if (dataStatus === 'failed') {
            generateNotify('', '该账号申请已被拒绝', 'danger');
        } else {
            //设置拒绝提示信息
            setSuggestions(3);

            var userId = $(this).attr('role');
            var status = 3; //拒绝
            data = {'user_id': userId, 'status': status};

            $('#msg_title').html('拒绝用户申请');
            // var ev = new EmailValidator();
            $('#cancel').html('取消');
            $('#modify-submit').html('确认拒绝');
            $('#modify-submit').show();
            $('#get-user-msg').modal('show');
        }
    });


    //删除用户申请
    $('.remove-account').click(function () {
        var id = $(this).attr('role');
        var dataStatus = $(this).attr('status');
        var data = {'id': id};
        console.log('dataStatus  :   ' + dataStatus);
        if (dataStatus == 'failed') { //如果是已完成或者申请失败， 直接删除
            removeaccount(data);
        } else {
            bootbox.confirm({
                message: '确定删除该用户吗?',
                buttons: {
                    confirm: {
                        label: '删除',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-danger'
                    }
                },
                callback: function (result) {
                    if (result)
                        removeaccount(data);
                }
            });
        }
    });


    //删除预约
    function removeaccount(data) {
        $.post('/account-delete', data, function (result) {
            console.log('result id : ' + result.id);
            if (result['id'] == 1) { //删除成功
                var pathname = window.location.pathname;
                $(location).attr('href', pathname);
                generateNotify('', result.msg, 'success');
            } else {
                generateNotify('', result.msg, 'danger');
            }
        });
    }

    $('.star').on('click', function () {
        $(this).toggleClass('star-checked');
    });

    $('.ckbox label').on('click', function () {
        $(this).parents('tr').toggleClass('selected');
    });

    $('.btn-filter').on('click', function () {
        var $target = $(this).data('target');
        if ($target != 'all') {
            $('.table tr').css('display', 'none');
            $('.table tr[data-status="' + $target + '"]').fadeIn('slow');
        } else {
            $('.table tr').css('display', 'none').fadeIn('slow');
        }
    });

    $("#suggestions").on("click", ".suggestion", function (event) {
        var value = event.currentTarget.textContent;
        // var msg = $(this).innerText;
        // console.log(' --- ', msg);
        console.log('value ', value);
        $('#msg-tf').val(value);
        // $("#msg-tf").prop('value', value);
    });

    //设置建议提示用户的信息
    function setSuggestions(type) {
        var suggestionUl = $('#suggestions li');
        var suggestions;
        if (type === 2) { //同意
            suggestions = accountSuccess;
        } else { //拒绝
            suggestions = accountFailed;
        }
        for (var i = 0; i < suggestionUl.length && i < suggestions.length; i++) {
            // suggestionUl[i].outerText = suggestions[i];
            // suggestionUl[i].val(suggestions[i]);
            // suggestionUl[i].text(suggestions[i]);
            suggestionUl[i].innerHTML = '<a class="label label-info">' + suggestions[i] + '</a>';
        }
    }
});